﻿using System;
using System.Text;
using BO.Infrastructure.StaticData;
using BO.Infrastructure.Utils;
using BO.News;
using GUI.Extensions;

namespace GUI.Controls.Photo
{
    public partial class BoxPhoto : System.Web.UI.UserControl
    {
        public bool GetDataFromNoCacheLayer = false;
        private const int Top = 3;
        private const int ImageWidth1 = 525;
        private const int ImageHeight1 = 350;
        private const int ImageWidth2 = 130;
        private const int ImageHeight2 = 80;

        protected void Page_Load(object sender, EventArgs e)
        {
            var objCat = RequestExtensions.Category;
            if (objCat != null)
            {
                var bo = GetDataFromNoCacheLayer && CacheSettingExtensions.EnableCacheHtml
                             ? NewsBO_NoCache.GetInstance()
                             : NewsBO.GetInstance();

                var dt = bo.GetNewsByType(Top, DefinedConstants.News.Types.PhotoNews, objCat.ParentId > 0 ? objCat.ParentId : objCat.Id);
                Visible = DataBind(dt);
                return;
            }
            Visible = false;

        }

        private bool DataBind(System.Data.DataTable dt)
        {
            if (dt != null && dt.Rows.Count > 0)
            {
                var r = dt.Rows[0];
                ltrAvatar.Text = PresentationUtils.Photo.BuildNewsAvatar(r, ImageWidth1, ImageHeight1);
                ltrTitle.Text = string.Format(
                    "<a href=\"{0}\" title=\"{2}\" class=\"title\">{1}</a>",
                    r[SqlConstants.NewsPublish.Url],
                    r[SqlConstants.NewsPublish.Title],
                    r[SqlConstants.NewsPublish.EncodedTitle]);
                ltrPublishedDate.Text = PresentationUtils.Object2DateTime(r[SqlConstants.NewsPublish.DistributionDate].ToString()).ToString("dd/mm/yyyy HH:mm");
                if (dt.Rows.Count > 1)
                {
                    var sb = new StringBuilder();
                    for (var i = 1; i < dt.Rows.Count; i++)
                    {
                        r = dt.Rows[i];
                        var avatar = PresentationUtils.Photo.BuildNewsAvatar(r, ImageWidth2, ImageHeight2);
                        sb.AppendFormat("<li>{3}<h2><a class=\"title\" title=\"{2}\" href=\"{0}\">{1}</a></h2></li>",
                            r[SqlConstants.NewsPublish.Url],
                            r[SqlConstants.NewsPublish.Title],
                            r[SqlConstants.NewsPublish.EncodedTitle],
                            avatar);
                    }
                    ltrOtherItem.Text = sb.ToString();
                }
                return true;
            }
            return false;
        }
    }
}